package models

import (
	"log"

	"common/utils"
)

type Account struct {
	Model
	UserName string `gorm:"size:64" json:"user_name" binding:"required"`
	Password string `gorm:"size:64" json:"password" binding:"required"`
}

// add
func (a *Account) AddAccount() (bool, error) {
	var check Account
	//判断是否存在此账号
	err1 := db.Where("user_name = ?", a.UserName).Find(&check).Error
	if err1 != nil {
		return false, err1
	}

	if check.UserName != "" {
		return false, err1
	}

	a.Password, _ = utils.PasswordHash(a.Password) //密码加密

	err := db.Create(a).Error

	log.Println("err:", err)
	return true, err
}

// login
func (a *Account) LoginAccount() (string, string, error) {
	var check Account //数据库那个结构体

	err := db.Where("user_name = ?", a.UserName).Find(&check).Error
	if err != nil {
		return "", "", err
	}

	if check.UserName == "" {
		return "", "无此账号", nil
	}

	match := utils.PasswordVerify(a.Password, check.Password) //密码验证

	if !match {
		return "", "账号或密码错误", nil
	}

	token, err := utils.CreateToken(check.UUID.String())
	if err != nil {
		return "", "登录失败", err
	}
	// log.Println(check.UUID.String())

	return token, "登录成功", nil
}

// del
func DelAccount(username string) error {

	err := db.Where("user_name = ?", username).Delete(&Account{}).Error
	log.Println("err:", err)
	return err
}
